package com.jh.paymentchannel.service;


import java.net.URI;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jh.paymentchannel.pojo.HLRegister;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;

@Service
public class HLPayTopupPage implements TopupRequest {

	private static final Logger log = LoggerFactory.getLogger(HLPayTopupPage.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	/*
	 * @Value("${sdj.org_no}") private String orgno;
	 * 
	 * @Value("${sdj.md5_key}") private static String md5key;
	 * 
	 * @Value("${sdj.base_url}") private String baseurl;
	 * 
	 * //修改t0的地址
	 * 
	 * @Value("${sdj.updatet0_url}") private String updatet0url;
	 * 
	 * //修改t1的地址
	 * 
	 * @Value("${sdj.updatet1_url}") private String updatet1url;
	 */

	@Value("${payment.ipAddress}")
	private String ipAddress;

	private String merchant_no = "C1800001614";

	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");

		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		String loginPhone = resultObj.getString("phone");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		String respCode = "";
		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			respCode = jsonObject.getString("resp_code");
		} catch (Exception e) {
			log.error("查询结算卡异常" + e.getMessage());
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "无默认结算卡,请绑定默认结算卡");
			return map;
		}

		if (!"000000".equals(respCode)) {
			map.put("resp_code", "failed");
			map.put("channel_type", "sdj");
			map.put("resp_message", "没有结算卡");
			return map;
		}

		// 结算卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");

		String cardType = resultObj.getString("cardType");
		// 银行名称
		String bankName = resultObj.getString("bankName");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");

		String cardtype = resultObj.getString("cardType");

		String expiredTime = resultObj.getString("expiredTime");

		String securityCode = resultObj.getString("securityCode");

		// 将银行名称进行更改
		String bankname = Util.queryBankNameByBranchName(bankName);

		// 通过结算卡查询是否更换结算卡
		HLRegister hlRegisterByJSK = topupPayChannelBusiness.getHLRegisterByBankCardAndCardType(cardNo, "2");

		HLRegister hlRegisterByPhoneAndCardType = topupPayChannelBusiness.getHLRegisterByPhoneAndCardType(phone, "2");

		// 通过信用卡查询是否绑定信用卡
		HLRegister hlRegisterByXYK = topupPayChannelBusiness.getHLRegisterByBankCardAndCardType(bankCard, "0");

		if (null == hlRegisterByPhoneAndCardType) {
			log.info("用户需要绑结算卡======");

			RestTemplate restTemplate2 = new RestTemplate();
			URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
			String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/settlementCardBind";
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("P1_bizType", "SettlementCardBind");
			requestEntity.add("P2_customerNumber", merchant_no);
			requestEntity.add("P3_userId", userid);
			requestEntity.add("P4_orderId", ordercode);
			requestEntity.add("P5_payerName", userName);
			requestEntity.add("P6_idCardType", "IDCARD");
			requestEntity.add("P7_idCardNo", idcard);
			requestEntity.add("P8_cardNo", cardNo);
			requestEntity.add("P9_phone", phone);
			requestEntity.add("P10_bankUnionCode", "");// 银行行号
			log.info("===================requestEntity==================" + requestEntity.toString());
			result = restTemplate2.postForObject(url2, requestEntity, String.class);
			log.info("===================result==================" + result.toString());
			JSONObject objs = JSONObject.fromObject(result);
			if ("绑结算卡成功".equals(objs.getString("message"))) {
				JSONObject jobj = objs.getJSONObject("json");
				if (jobj.containsKey("rt7_bindStatus") && "FAIL".equals(jobj.getString("rt7_bindStatus"))) {
					map.put("resp_code", "999999");
					map.put("resp_message", "绑卡失败");
					return map;
				}
				String bindId = jobj.getString("rt10_bindId");
				url2 = uri2.toString() + "/v1.0/paymentchannel/hlregister/add";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("userId", userid);
				requestEntity.add("exemption", "0");
				requestEntity.add("cardNo", idcard);
				requestEntity.add("phone", phone);
				requestEntity.add("name", userName);
				requestEntity.add("bindId", bindId);
				requestEntity.add("bankName", bankName);
				requestEntity.add("bankCard", cardNo);
				requestEntity.add("loginPhone", loginPhone);
				requestEntity.add("cardType", "2");
				requestEntity.add("status", "0");
				requestEntity.add("balance", "0");
				requestEntity.add("frozenBalance", "0");
				log.info("===================requestEntity==================" + requestEntity.toString());
				result = restTemplate2.postForObject(url2, requestEntity, String.class);
				log.info("===================result==================" + result.toString());
				JSONObject obj = JSONObject.fromObject(result);
				JSONObject rlt = obj.getJSONObject("result");
				/*
				 * map.put("resp_code", "000000"); map.put("result", rlt.getString("bindId"));
				 * map.put("resp_message", "绑卡成功");
				 */
				log.info("绑定结算卡成功=======");

				if (null == hlRegisterByXYK) {
					log.info("用户需要绑定信用卡=======");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybankinfo" + "?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&cardName=" + URLEncoder.encode(cardName, "UTF-8")
							+ "&bankCard=" + bankCard + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&securityCode=" + securityCode + "&expiredTime=" + expiredTime + "&isBindCard=1");
					return map;

				} else {
					log.info("发起支付=====");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybankinfo" + "?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&cardName=" + URLEncoder.encode(cardName, "UTF-8")
							+ "&bankCard=" + bankCard + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&securityCode=" + securityCode + "&expiredTime=" + expiredTime + "&isBindCard=2");
					return map;
				}

			} else {
				map.put("resp_code", "999999");
				map.put("resp_message", objs.getString("message"));
				return map;
			}

		} else {
			String bankCard2 = hlRegisterByPhoneAndCardType.getBankCard();
			log.info("用户已经绑定的结算卡======bankCard2====" + bankCard2);

			if (cardNo != bankCard2 && !cardNo.equals(bankCard2)) {
				log.info("用户更换了结算卡=========");
				RestTemplate restTemplate2 = new RestTemplate();
				URI uri2 = util.getServiceUrl("paymentchannel", "error url request!");
				String url2 = uri2.toString() + "/v1.0/paymentchannel/topup/bindCardUnbind";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("P1_bizType", "BankCardUnbind");
				requestEntity.add("P2_customerNumber", merchant_no);
				requestEntity.add("P3_userId", userid);
				requestEntity.add("P4_bindId", hlRegisterByPhoneAndCardType.getBindId());
				requestEntity.add("P5_orderId", ordercode);
				requestEntity.add("P6_timestamp", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
				log.info("===================requestEntity==================" + requestEntity.toString());
				result = restTemplate2.postForObject(url2, requestEntity, String.class);
				log.info("===================result==================" + result.toString());
				JSONObject objs = JSONObject.fromObject(result);
				if ("结算卡解绑成功".equals(objs.getString("message"))) {
					log.info("结算卡解绑成功=======");
					log.info("开始重新绑结算卡====");
					restTemplate2 = new RestTemplate();
					uri2 = util.getServiceUrl("paymentchannel", "error url request!");
					url2 = uri2.toString() + "/v1.0/paymentchannel/topup/settlementCardBind";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("P1_bizType", "SettlementCardBind");
					requestEntity.add("P2_customerNumber", merchant_no);
					requestEntity.add("P3_userId", userid);
					requestEntity.add("P4_orderId", ordercode);
					requestEntity.add("P5_payerName", userName);
					requestEntity.add("P6_idCardType", "IDCARD");
					requestEntity.add("P7_idCardNo", idcard);
					requestEntity.add("P8_cardNo", cardNo);
					requestEntity.add("P9_phone", phone);
					requestEntity.add("P10_bankUnionCode", "");// 银行行号
					log.info("===================requestEntity==================" + requestEntity.toString());
					result = restTemplate2.postForObject(url2, requestEntity, String.class);
					log.info("===================result==================" + result.toString());
					JSONObject obj = JSONObject.fromObject(result);
					if ("绑结算卡成功".equals(obj.getString("message"))) {
						JSONObject jobj = obj.getJSONObject("json");
						if (jobj.containsKey("rt7_bindStatus") && "FAIL".equals(jobj.getString("rt7_bindStatus"))) {
							map.put("resp_code", "999999");
							map.put("resp_message", "绑卡失败");
							return map;
						}
						String bindId = jobj.getString("rt10_bindId");
						// hlRegisterByPhoneAndCardType.setUserId(userid);
						// hlRegisterByPhoneAndCardType.setCardNo(idcard);
						hlRegisterByPhoneAndCardType.setPhone(phone);
						hlRegisterByPhoneAndCardType.setBankCard(cardNo);
						hlRegisterByPhoneAndCardType.setBankName(bankName);
						hlRegisterByPhoneAndCardType.setBindId(bindId);
						log.info("更换结算卡成功=======");

						if (null == hlRegisterByXYK) {
							log.info("用户需要绑定信用卡=======");
							map.put("resp_code", "success");
							map.put("channel_type", "jf");
							map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybankinfo"
									+ "?bankName=" + URLEncoder.encode(bankname, "UTF-8") + "&bankNo=" + cardNo
									+ "&amount=" + amount + "&ordercode=" + ordercode + "&cardType="
									+ URLEncoder.encode(cardType, "UTF-8") + "&ipAddress=" + ipAddress + "&cardName="
									+ URLEncoder.encode(cardName, "UTF-8") + "&bankCard=" + bankCard + "&cardtype="
									+ URLEncoder.encode(cardtype, "UTF-8") + "&securityCode=" + securityCode
									+ "&expiredTime=" + expiredTime + "&isBindCard=1");
							return map;

						} else {
							log.info("发起支付=====");
							map.put("resp_code", "success");
							map.put("channel_type", "jf");
							map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybankinfo"
									+ "?bankName=" + URLEncoder.encode(bankname, "UTF-8") + "&bankNo=" + cardNo
									+ "&amount=" + amount + "&ordercode=" + ordercode + "&cardType="
									+ URLEncoder.encode(cardType, "UTF-8") + "&ipAddress=" + ipAddress + "&cardName="
									+ URLEncoder.encode(cardName, "UTF-8") + "&bankCard=" + bankCard + "&cardtype="
									+ URLEncoder.encode(cardtype, "UTF-8") + "&securityCode=" + securityCode
									+ "&expiredTime=" + expiredTime + "&isBindCard=2");
							return map;
						}

					} else {
						map.put("resp_code", "999999");
						map.put("resp_message", objs.getString("message"));
						return map;
					}

				}else {
					map.put("resp_code", "999999");
					map.put("resp_message", objs.getString("message"));
					return map;
				}

			} else {

				if (null == hlRegisterByXYK) {
					log.info("用户需要绑定信用卡=======");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybankinfo" + "?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&cardName=" + URLEncoder.encode(cardName, "UTF-8")
							+ "&bankCard=" + bankCard + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&securityCode=" + securityCode + "&expiredTime=" + expiredTime + "&isBindCard=1");
					return map;

				} else {
					log.info("发起支付=====");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/tohlpaybankinfo" + "?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankNo=" + cardNo + "&amount=" + amount
							+ "&ordercode=" + ordercode + "&cardType=" + URLEncoder.encode(cardType, "UTF-8")
							+ "&ipAddress=" + ipAddress + "&cardName=" + URLEncoder.encode(cardName, "UTF-8")
							+ "&bankCard=" + bankCard + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&securityCode=" + securityCode + "&expiredTime=" + expiredTime + "&isBindCard=2");
					return map;
				}

			}
		}

	}

}
